package com.hsc.www.oschina;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MyController {

    private RestTemplate restTemplate = new RestTemplate();


    String clientId = "oschina";
    String clientSecret = "123456";

    String scope = "user";



    String publicSourceUrl = "http://localhost:8082/publicSource";
    String userSourceUrl = "http://localhost:8082/userSource";
    String adminSourceUrl = "http://localhost:8082/adminSource";

    @RequestMapping(value = {"/", "login"})
    public String login(HttpServletRequest request) throws Exception {
        return "login";
    }


    @RequestMapping("/thirdRegister")
    public String githubLogin(HttpServletRequest request, String authType) throws Exception {
        String path = null;
        if ("github".equals(authType)) {
            path = new StringBuilder()
                    .append("redirect:")
                    .append("http://localhost:8081/oauth/authorize")
                    .append("?client_id=").append(clientId)
                    .append("&response_type=").append("code")
                    .append("&redirect_uri=").append(URLEncoder.encode("http://127.0.0.1:8083/code", "UTF-8"))
                    .toString();
        }
        return path;
    }

    @ResponseBody
    @RequestMapping("code")
    public Object code(String code, String error, String error_description) {
        if (code == null || code.equals("")) {
            System.out.println("error=" + error);
            System.out.println("error_description=" + error_description);
            return error_description;
        } else {

            //Http Basic 验证
            String clientAndSecret = clientId + ":" + clientSecret;
            clientAndSecret = "Basic " + Base64.getEncoder().encodeToString(clientAndSecret.getBytes());
            //head
            HttpHeaders head = new HttpHeaders();
            head.set("Authorization", clientAndSecret);
            head.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //body
            MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
            body.put("code", Collections.singletonList(code));
            body.put("redirect_uri", Collections.singletonList("http://127.0.0.1:8083/code"));
            body.put("grant_type", Collections.singletonList("authorization_code"));
            //HttpEntity
            HttpEntity httpEntity = new HttpEntity(body, head);
            //获取 Token
            ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.exchange(
                    "http://localhost:8081/oauth/token",
                    HttpMethod.POST,
                    httpEntity,
                    OAuth2AccessToken.class
            );
            System.out.println("token获取成功：token=" + JSONObject.toJSONString(responseEntity));
            OAuth2AccessToken oAuth2AccessToken = responseEntity.getBody();

            Map map = new HashMap();
            map.put("token", oAuth2AccessToken);
            map.put("publicSource", getResource(oAuth2AccessToken, publicSourceUrl));
//            map.put("userSourceUrl", getResource(oAuth2AccessToken, userSourceUrl));
//          map.put("adminSourceUrl", getResource(oAuth2AccessToken, adminSourceUrl));

            return map;

        }

    }


    public WebResponse getResource(OAuth2AccessToken oAuth2AccessToken, String sourceUrl) {
        HttpHeaders head = new HttpHeaders();
        head.set("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + oAuth2AccessToken.getValue());
        HttpEntity httpEntity = new HttpEntity(null, head);
        ResponseEntity<WebResponse> responseEntity = restTemplate.exchange(sourceUrl, HttpMethod.POST, httpEntity, WebResponse.class);
        WebResponse webResponse= responseEntity.getBody();
        return webResponse;
    }


}
